package com.itfreer.data.general;

import android.content.Context;

import com.itfreer.data.general.cache.LocalCache;
import com.itfreer.data.general.configuration.DefulatConfig;
import com.itfreer.data.sqlite.SqliteWorkspaceClass;

import java.util.HashMap;

/**
 * 定义工作空间工厂类 2014.6.4
 */
public class WorkspaceFactoryClass implements IWorkspaceFactory{

    public static final WorkspaceFactoryClass install = new WorkspaceFactoryClass();

	public static Object LOCA_OBJECT = new Object();

    private WorkspaceFactoryClass(){

    }

	/**
	 * 创建工作空间，根据配置节名称
	 */
	@Override
	public IWorkspace openWorkspace(Context context) {
		// 解析连接信息
		ConnectionInfo info = new ConnectionInfo(null);
		info.setDatabase(DefulatConfig.defulatConfig.Database);
		info.setPassword(DefulatConfig.defulatConfig.Password);
		info.setUserID(DefulatConfig.defulatConfig.UserID);
		info.setVersion(DefulatConfig.defulatConfig.Version);
		info.setWorkspaceType(WorkspaceType
				.getWorkspaceTypeByTypeId(DefulatConfig.defulatConfig.DbProvideType));
		return openDbWorkspace(context, info);
	}

	/**
	 * 创建工作空间，根据给定的工作空间信息
	 */
	@Override
	public IWorkspace openDbWorkspace(Context context, ConnectionInfo info) {
		if (info == null)
			return null;

		String key = info.getConnectionStr() + "_" + info.getWorkspaceType().toString() + "_DB";
		HashMap<String, IWorkspace> workspaceCache = LocalCache.getWorkspaceCache();
		synchronized (LOCA_OBJECT) {
			if (workspaceCache.containsKey(key)) {
				return workspaceCache.get(key);
			} else {
                IWorkspace adoWorkspace = null;
                if(info.getWorkspaceType() == WorkspaceType.Sqlite){
                    adoWorkspace = new SqliteWorkspaceClass(context, info);
                }
				workspaceCache.put(key, adoWorkspace);
				return adoWorkspace;
			}
		}
	}
}